<?php
namespace Modules\File\Library;

use Phalcon\Di;
use Core\File;
use Modules\File\Models\File as FileModel;

class FileHandle
{
    public static function upload($params = [], $name = null)
    {
        $di = Di::getDefault();
        $output = array('error' => [], 'success' => []);
        $params += [
            'fileType' => [
                'jpeg' => 'jpeg',
                'png' => 'png',
                'jpg' => 'jpg',
                'gif' => 'gif',
            ],
            'limit' => 10,
            'num' => 1,
            'fileAccess' => 20,
            'minSize' => 10,
            'maxSize' => 900,
        ];

        $config = self::config($params);
        if ($config['fileAccess'] === false) {
            return $output;
        }

        $num = 1;
        // Print the real file names and sizes
        foreach ($di->getShared('request')->getUploadedFiles(true) as $file) {
            //只处理选定文件
            if ($name != null) {
                if (is_string($name)) {
                    if ($file->getKey() != $name) {
                        continue;
                    }
                } elseif (is_array($name)) {
                    if (array_search($file->getKey(), $name) === false) {
                        continue;
                    }
                }
            }

            $fileName = $file->getName();
            $fileSize = $file->getSize();
            $fileNameInfo = explode('.', $fileName);
            $fileExtension = end($fileNameInfo);
            if ($num > $params['limit']) {
                $output['error'][] = array(
                    'fileName' => $fileName,
                    'flash' => '文件被忽略，超过单次上传文件数量上限：' . $params['num'],
                );
                continue;
            }

            if ($config['fileType']) {
                if (!isset($config['fileType'][strtolower($fileExtension)])) {
                    $output['error'][] = array(
                        'fileName' => $fileName,
                        'flash' => '文件类型不支持：'.$fileExtension,
                    );
                    continue;
                }
            }

            if (isset($config['max'])) {
                if ($fileSize/1000 > $config['max']) {
                    $output['error'][] = array(
                        'fileName' => $fileName,
                        'flash' => '文件过大',
                    );
                    continue;
                }
            }
            if ($config['min']) {
                if ($fileSize < $config['min']) {
                    $output['error'][] = array(
                        'fileName' => $fileName,
                        'flash' => '文件过小',
                    );
                    continue;
                }
            }
            //预留匿名上传逻辑
            if (isset($params['dir'])) {
                $urlDir = $params['dir'];
            } else {
                $urlDir = 'file/' . $fileExtension . date('/Y/m/d/');
            }

            if (isset($params['fileName'])) {
                $newFileName = $params['fileName'];
            } else {
                $newFileName = md5($fileName) . '.' . $fileExtension;
            }

            if($params['fileAccess'] < 20){
                //私有上传
                $reDir = 'Web/' . WEB_CODE . '/' . $urlDir; //文件的相对目录地址
                $obDir = ROOT_DIR . $reDir; //文件的绝对目录地址
            }elseif ($params['fileAccess'] >= 20){
                //共有上传
                $reDir = WEB_CODE.'/' . $urlDir;//文件的相对目录地址
                $obDir = ROOT_DIR . '/' . $reDir;//文件的绝对目录地址
            }
            //Print file details
            //echo $file->getName(), " ", $file->getSize(), "\n";

            //Move the file into the application
            if (!file_exists($obDir)) {
                @File::mkdir($reDir);
            }
            if (!is_writable($obDir) && file_exists($obDir)) {
                chmod($obDir, 0755);
            }
            if (file_exists($obDir)) {

                //echo $fileName;
                $fileObPath = $obDir . $newFileName;
                $fileModel = new FileModel();
                $fileModel->access = intval($params['fileAccess']);
                $fileModel->extension = $fileExtension;
                //$fileModel->uid = $di->getShared('user');
                $fileModel->dir = $urlDir;
                $fileModel->name = $newFileName;
                $fileModel->created = time();
                $fileModel->changed = time();
                if($di->getShared('user')->isLogin() === false){
                    $fileModel->uid = $di->getShared('user')->getUid();
                }else{
                    $fileModel->anonymous = $di->getShared('user')->getUid();
                }
                if ($fileModel->save()) {
                    if ($file->moveTo($fileObPath)) {
                        //$waterMark = new Watermask($fileAbName);
                        //$waterMark->output();
                        //unset($waterMark);
                        $num++;
                        $output['success'][] = array(
                            'fileName' => $newFileName,
                            'url' => $fileModel->getUrl(),
                            'oldFileName' => $fileName,
                            'id' => $file->getKey(),
                            'flash' => '文件上传成功',
                        );
                    } else {
                        $output['error'][] = array(
                            'fileName' => $newFileName,
                            'url' => $fileModel->getUrl(),
                            'oldFileName' => $fileName,
                            'id' => $file->getKey(),
                            'flash' => '文件移动失败',
                        );
                    }
                } else {
                    $output['error'][] = array(
                        'oldFileName' => $fileName,
                        'flash' => '文件信息录入数据库失败',
                    );
                }
            }
        }
        return $output;
    }

    public static function config($settings)
    {
        $di = Di::getDefault();
        $output = [
            'fileType' => [],
            'min' => 10,
            'max' => 400,
            'fileAccess' => false,
            'rename' => true
        ];
        $settings += [
            'fileType' => [
                'jpeg' => 'jpeg',
                'png' => 'png',
                'jpg' => 'jpg',
                'gif' => 'gif',
            ],
            'fileAccess' => 10,
            'minSize' => 10,
            'maxSize' => 900,
        ];
        $baseConfig = $di->getShared('config')->get('m.file.config');
        //角色权限判断
        $roles = $di->getShared('user')->getRoles();
        foreach ($roles as $role) {
            //允许的类型
            if (isset($settings['fileType'])) {
                $output['fileType'] = $settings['fileType'];
            } else {
                if (isset($baseConfig[$role . '_upload_type'])) {
                    $output['fileType'] = array_merge($output['fileType'], $baseConfig[$role . '_upload_type']);
                }
            }

            //最小文件尺寸
            if (isset($settings['minSize'])) {
                $output['min'] = $settings['minSize'];
            } else {
                if (isset($output['min'])) {
                    if (isset($baseConfig[$role . '_upload_size_min']) && $output['min'] > $baseConfig[$role . '_upload_size_min']) {
                        $output['min'] = isset($baseConfig[$role . '_upload_size_min']);
                    }
                } else {
                    if (isset($baseConfig[$role . '_upload_size_min'])) {
                        $output['min'] = isset($baseConfig[$role . '_upload_size_min']);
                    }
                }
            }

            //最大文件尺寸
            if (isset($settings['maxSize'])) {
                $output['max'] = $settings['maxSize'];
            } else {
                if (isset($output['max'])) {
                    if (isset($baseConfig[$role . '_upload_size_max']) && $output['max'] > $baseConfig[$role . '_upload_size_max']) {
                        $output['max'] = isset($baseConfig[$role . '_upload_size_max']);
                    }
                } else {
                    if (isset($baseConfig[$role . '_upload_size_max'])) {
                        $output['max'] = isset($baseConfig[$role . '_upload_size_max']);
                    }
                }
            }

            //共有文件上传权限
            if ($settings['fileAccess'] >= 20) {
                if (isset($baseConfig[$role . '_upload_access']['public'])) {
                    $output['fileAccess'] = true;
                }
            }

            //私有文件上传权限
            if ($settings['fileAccess'] < 20) {
                if (isset($baseConfig[$role . '_upload_access']['private'])) {
                    $output['fileAccess'] = true;
                }
            }
        }

        if (isset($settings['rename'])) {
            $output['rename'] = $settings['rename'];
        } elseif (isset($baseConfig['rename'])) {
            $output['rename'] = $baseConfig['rename'];
        }

        return $output;
    }

    public static function delete()
    {

    }

    public static function editor()
    {

    }
}
